package com.pay.ioopos.support.scan;

import androidx.lifecycle.LifecycleOwner;

import com.pay.ioopos.ScanListener;

public class ScanLife implements ScanCase {
    private boolean isScaned = false;
    private ScanCase[] cases;
    private ScanListener listener;

    public ScanLife(ScanCase ...cases) {
        this.cases = cases;
    }

    @Override
    public void bindToLifecycle(LifecycleOwner owner) {
        int num = cases.length;
        for (int i = 0; i < num; i++) {
            if (null != cases[i]) {
                cases[i].bindToLifecycle(owner);
                cases[i].setScanListener(createListener());
            }
        }
    }

    @Override
    public void setScanListener(ScanListener listener) {
        this.listener = listener;
    }

    private ScanListener createListener() {
        return new ScanListener() {

            @Override
            public boolean onScan(String code) {
                if (isScaned) {
                    return true;
                }
                isScaned = true;
                return isScaned = (null != listener ? listener.onScan(code): true);
            }

            @Override
            public void onError(String msg) {
                if (null != listener) {
                    listener.onError(msg);
                }
            }
        };
    }
}
